/**
 * 
 */
package com.shine.cotrun.web.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * 附件过滤器，过滤UploadConfig.rootFolder设置的路径，如/upload/*
 * 
 * @author 卓诗垚
 * @version May 8, 2007
 */
public class FileFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected String fileNameEncoding;/////要制定的编码，在web.xml中配置
	protected String fileNameToEncoding;/////要制定的编码，在web.xml中配置
	
	public void init(FilterConfig config) throws ServletException {
		fileNameEncoding = config.getInitParameter("fileNameEncoding");///得到在web.xml中配置的编码
		fileNameToEncoding = config.getInitParameter("fileNameToEncoding");///得到在web.xml中配置的编码
	}
	
	public void destroy() {
		fileNameEncoding = null;
		fileNameToEncoding = null;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, 
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpReq = (HttpServletRequest) request;
		HttpServletResponse httpResp = (HttpServletResponse) response;
		//链接防盗
		if (FileDispatcher.getConfig().isEnableRefererCheck()) {//是否开启
			String referer = httpReq.getHeader("referer");
			if (referer != null && !FileDispatcher.getConfig().isAccreditHost(referer)) {
				httpResp.sendError(HttpServletResponse.SC_NOT_FOUND);
				return;
			}
		}
		
		//图片转向
		String reqStr = httpReq.getServletPath();
		//中文文件名编码转换
		if (fileNameEncoding != null && fileNameToEncoding != null) {
			reqStr = new String(reqStr.getBytes(fileNameEncoding), fileNameToEncoding);
		}
		FileInputStream imgStream = null;
		try {
			File file = FileDispatcher.findFile(reqStr);
			if (file != null) {
				imgStream = new FileInputStream(file);
				int i = imgStream.available(); //得到文件大小
				try {
					String type = reqStr.substring(reqStr.lastIndexOf("."));
					if(FileDispatcher.getConfig().isImgExt(type)) {
						httpResp.setContentType("image/*");	//设置文件类型
					} else if (".html.htm".indexOf(type.toLowerCase()) >= 0) {
						httpResp.setContentType("text/html");
					} else {
						httpResp.setContentType("application/*");
						httpResp.setHeader("Content-disposition","attachment" );//默认附件(attachment)下载(TXT默认是内联(inline))
					}
				} catch(Exception e) {
					httpResp.setContentType("application/*");
				}
				httpResp.setContentLength(i);		//设置文件大小
				OutputStream toClientStream = httpResp.getOutputStream();	//得到输出流Servlet流不用关闭
				byte data[] = new byte[1024];
				//逐步输出数据
				while( (i = imgStream.read(data)) > 0){
					toClientStream.write(data,0,i);
				}
				toClientStream.flush();
			} else {
				filterChain.doFilter(httpReq, httpResp);
			}
		} catch(IOException e) {
			throw e;
		} finally {
			if (imgStream != null) {
				imgStream.close();
			}
		}
	}
}
